package lihao3.Test3;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) throws Exception {


        File file = new File("D:\\goods.txt");
        Test test = new Test();
        if (!file.exists()) {
            List<Goods> goodsList = new ArrayList<>();
            Goods goods1 = new Goods();
            goods1.setId(1);
            goods1.setName("华为手机");
            goods1.setNum(10);
            goods1.setPrice(5000);

            Goods goods2 = new Goods();
            goods2.setId(2);
            goods2.setName("苹果手机");
            goods2.setNum(20);
            goods2.setPrice(5000);

            goodsList.add(goods1);
            goodsList.add(goods2);
            test.serial(goodsList);
        }

        List<Goods> goodsList = test.deserial();
        Scanner myScanner = new Scanner(System.in);
        //接收用户的输入
        System.out.println("请输入商品名字");
        String name = myScanner.next();

        for (Goods goods : goodsList) {
            if (name.equals(goods.getName())) {
                System.out.println("请输入购买量");
                int num = myScanner.nextInt();
                System.out.println("==========购买小票:=======");
                System.out.println("商品名称:" + goods.getName());
                System.out.println("商品单价:" + goods.getPrice());
                System.out.println("商品小计:" +  num * goods.getPrice());
            }
        }

    }

    // 序列化方法
    private void serial(List<Goods> goodsList){
        try {
            // FileOutputStream流是指文件字节输出流，
            // 专用于输出原始字节流如图像数据等，其继承OutputStream类，拥有输出流的基本特性
            FileOutputStream fileOutputStream = new FileOutputStream("D:\\goods.txt");
            // 对象的序列化流，作用：把对象转成字节数据的输出到文件中保存，
            // 对象的输出过程称为序列化，可实现对象的持久存储。
            ObjectOutputStream objectOutputStream= new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(goodsList);
            objectOutputStream.flush();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }


    // 反序列化方法
    public List<Goods> deserial() {
        try {
            FileInputStream fis = new FileInputStream("D:\\goods.txt");
            // ObjectInputStream 反序列化流，
            // 将之前使用 ObjectOutputStream 序列化的原始数据恢复为对象，以流的方式读取对象。
            // 构造方法 ObjectInputStream(InputStream in) 创建从指定 InputStream 读取的 ObjectInputStream。
            ObjectInputStream ois = new ObjectInputStream(fis);
            List<Goods> goods = (List<Goods>) ois.readObject();
            ois.close();
            System.out.println(goods.toString());
            return goods;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
